package com.snowflakes.gruntr;

import java.util.Locale;

import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AddFriend extends Activity {	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.add_friend);
		
		final EditText friendEmail = (EditText) findViewById(R.id.etFriendEmail);
		Button submitRequest = (Button) findViewById(R.id.bSubmitFriendRequest);
		
		//final Context context = getApplicationContext();
		
		
		submitRequest.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				if(friendEmail.equals("")){
					Toast.makeText(getBaseContext(), "Enter an email address of a friend first", Toast.LENGTH_LONG)
					.show();
				}
				else{
					String frEmail = friendEmail.getText().toString();
					frEmail = frEmail.toLowerCase(Locale.getDefault());
					
					ParseQuery<ParseUser> idQuery = ParseQuery.getQuery("_User");
					idQuery.whereEqualTo("email", frEmail);					
					
					idQuery.getFirstInBackground(new GetCallback<ParseUser>() {
						public void done(ParseUser returnedUser, ParseException e) {
							if (returnedUser == null) {
								Toast.makeText(getBaseContext(), "User not found", Toast.LENGTH_LONG)
								.show();
							}
							else {
								ParseUser user = ParseUser.getCurrentUser();
								
								ParseObject friendRequest = new ParseObject("FriendRequests");
								friendRequest.put("Sender", user);
								friendRequest.put("Recipient", returnedUser);
								friendRequest.put("Accepted", "false");
								friendRequest.put("Denied", "false");
								friendRequest.put("From", user.get("name"));
								friendRequest.saveInBackground();
								
								Toast.makeText(getBaseContext(), "Friend request sent", Toast.LENGTH_LONG)
								.show();
								
								finish();
							}
						}
					});
				}
				
			}
		});
		
	}
	
	
	
}
